package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务
 */
@Component
@Slf4j
public class MyTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 处理超时订单,每分钟执行一次
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeoutOrder(){
        log.info("处理超时订单:{}" , LocalDateTime.now());

        //查询超时订单,15分钟
      List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));

        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                //修改订单状态为6,取消订单
                orders.setStatus(Orders.CANCELLED);
                //取消原因
                orders.setCancelReason("订单超时，自动取消");
                //取消时间
                orders.setCancelTime(LocalDateTime.now());
                //修改订单
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理一直在派送中的订单,每天凌晨1点执行一次
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("处理派送中的订单:{}" , LocalDateTime.now());
        //查询派送中的订单，把前一天的派送订单改为已完成
        List<Orders> ordersList =  orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));

        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                //修改订单状态为5,完成订单
                orders.setStatus(Orders.COMPLETED);
                //修改订单
                orderMapper.update(orders);
            }
        }

    }
}
